<template>
	<div ref="chatPage">
		<div class="header">
			<mu-appbar key="detail" style="position:fixed;top:0;left:0;">
				<span class="iconfont" @touchend="$router.go(-1)" slot="left">&#xe61f;</span>
				<span solt="default" style="font-size: 16px;">{{vue_title}}</span>
			</mu-appbar>
		</div>
		<div class="list" ref="listWrap">
			<div class="loadingText">
				<span class="loadBtn" @touchend="vFun_loading_btn" v-if="vue_loading_btnShow">
		  		点击加载更多消息
		  	</span>
				<span class="loading" ref="loading" v-else>
			  	<i class="iconfont" ref="loadingIcon"></i>
			  	加载中..
			</span>
			</div>
			<mu-list ref="list">
				<mu-list-item v-for="(item,index) in vue_listData" disableRipple to="#/" :class="{mySay:item.userName=='my',otherSay:item.userName!='my'}"  v-if="item !=null">
					<mu-avatar :src="vue_detail_headLogo" slot="rightAvatar" v-show="item.userName=='my'" v-if="item !=null"/>
					<mu-avatar :src="vue_detail_headLogo" slot="left" v-show="item.userName!='my'"  v-if="item !=null"/>
					<mu-content-block class="contentDiv"  v-html="item.userSay"  v-if="item !=null">
						{{item.userSay}}
					</mu-content-block>
				</mu-list-item>
			</mu-list>
		</div>
		<div class="footer" ref="footer">
			<div class="inputBtn">
				<div class="input">
					<mu-text-field @focus="vFun_inputFocus" v-model="vue_chat_mySay" multiLine hintText="" /><br/>
				</div>
				<div class="button">
					<span class="iconfont em" @touchend="vFun_emojis">&#xe669;</span>
					<mu-raised-button @click="vFun_push" label="发送" class="demo-raised-button" primary/>
				</div>
			</div>
			<div class="emojis" ref="emojis" v-show="vue_emojis_show&&!vue_keyboard_show">
				<ul class="clearfix">
					<li class="fl" v-for="(item,index) in vue_emojis" @touchend="vFun_emojis_select(item)" v-html="item.innerHTML"></li>
				</ul>
			</div>




		</div>
	</div>
</template>
<script>
	export default {

		data() {
			return {
				vue_title: "", //头部标题
				vue_listData: [], //会话列表vue_listData
				vue_screenHeight: document.documentElement.clientHeight, //页面高度，用来做监听
				vue_resizeHeight: 0, //页面高度，用来做监听
				vue_emojis: null, //获取全部表情
				vue_emojis_show: false, //表情是否显示
				vue_keyboard_show: false, //键盘是否弹出
				vue_footer_maxHeight: null, //用来记录footer之前的高度
				vue_chat_mySay: "", //发送的消息
				vue_deg_num: 0, //下拉加载的icon旋转数值
				vue_deg_paly: null, //loading图标转动的定时器
				vue_loading_btnShow: true, //是否显示加载按钮
				vue_chatDetailList_oldHeight: 0, //对话页面之前的高度，用来给scroll定位
				rongcloudUser : null,
				rong_key: "",
				rong_token : "",
				target_targetId : "",
				BasicMemberAndMemberOperatorData : null,
				customerUser : null,
				vue_detail_headLogo:require('../../assets/images/IM_detail.png')
			}
		},
		watch: {
			vue_screenHeight(val, oldVal) { //用来监听window.resize事件
				if(!this.timer) {
					this.vue_screenHeight = val;
					this.timer = true;
					let that = this;
					this.$refs['listWrap'].style.marginBottom = this.$refs['footer'].clientHeight + _this.vue_resizeHeight + 'px';
					setTimeout(function() {
						that.timer = false
					}, 10)
				}
			},
			vue_keyboard_show(val) {
				if(val) {
					this.vue_emojis_show = false;
				}
			},
			vue_emojis_show(val) {
				setTimeout(() => {
					if(val) {
						this.vue_footer_maxHeight = this.$refs['footer'].clientHeight;
					}
					this.$refs['listWrap'].style.marginBottom = this.$refs['footer'].clientHeight + 'px';
					window.scrollTo(0, this.$refs['chatPage'].clientHeight) //页面滚动到底部
				}, 1)
			},
			vue_chatDetailList_oldHeight(val, oldVal) {
				window.scrollTo(0, val - oldVal)
			},
			vue_listData(val, oldVal) {
				setTimeout(() => {
					this.vue_chatDetailList_oldHeight = this.$refs['listWrap'].clientHeight;
				}, 10)
			},
		},
		methods: {
			vFun_userInfo(){
				if(localStorage.getItem("memberCode")==null){  //判断有没有登录
			     	this.$router.push({path:"/landing"})
				}
                else{
	 				this.axios({
					    method: 'GET',
					    url: "/v3/rongcloud/users/getCurrentUserData",
			     	}).then((res) => {
			     		this.rongcloudUser = res.data;
			     		console.log('获取当前登录用户信息：' + this.rongcloudUser);
			     		this.vue_title = "在线客服";

			     		this.rong_key = (this.rongcloudUser != null) ? this.rongcloudUser.appKey : "";
			     		this.rong_token = (this.rongcloudUser != null) ? this.rongcloudUser.userToken : "";
						this.rong_targetId = (this.rongcloudUser != null) ? this.rongcloudUser.platUserId : "";

						this.vFun_messageHistory();
					}).catch((err)=>{
					    //this.Public.openError(this,err.response.data)
				    });
                }
			},
			vFun_emojis() { //点击表情按钮
				if(!this.vue_keyboard_show) { //键盘没有弹出时
					this.vue_emojis_show = !this.vue_emojis_show
				} else { //键盘弹出时
					setTimeout(() => { //
						this.vue_emojis_show = true;
						this.$refs['listWrap'].style.marginBottom = this.$refs['footer'].clientHeight + 'px';
						window.scrollTo(0, this.$refs['chatPage'].clientHeight) //页面滚动到底部
					}, 1)
				}
			},
			vFun_push() { //点击发送按钮
				let __this = this;
				var $scope = new Object();
				$scope.targetType = 1; //1：私聊
				//var appKey = (this.rongcloudUser != null && this.rongcloudUser.appKey != null) ? this.rongcloudUer.appKey :　"3argexb6r934e";
				//var userToken = (this.rongcloudUser != null && this.rongcloudUser.userToken != null) ? this.rongcloudUer.userToken :　"b/jvjEFD41TIVT0nsf9+L3ryPPkHsvRwWZV8SVI5ICcZ2I5Nl4OdNO01OjZxjjmVlD2dmk4RZ90=";
				var config = {
					appkey: this.rong_key,
					token: this.rong_token
				};
				if(this.vue_chat_mySay) {

					var msgObj = {
						type: 　1,
						targetId: this.rong_targetId,
						msg: new RongIMLib.TextMessage({
							content: this.vue_chat_mySay
						})
					};
					this.RongcloudMessage.save(config, msgObj, {
						onSuccess: function(message) {
							__this.vue_listData[__this.vue_listData.length] = {
								userHead: require('../../assets/images/logo10.jpg'),
								userName: 'my',
								userSay: __this.vue_chat_mySay,
								start: 'rightAvatar',
								num: '0'
							};
							__this.vue_chat_mySay = "";
							setTimeout(() => {
								window.scrollTo(0, __this.$refs['chatPage'].clientHeight) //页面滚动到底部
							}, 10)
						},
						onError: function(error) {
							console.log('发送消息失败：' + error);
						}
					});
				};
			},
			vFun_inputFocus() { //

			},
			vFun_loading_play() { //调用loading转动
				clearInterval(this.vue_deg_paly); //先清除之前的定时器
				this.vue_deg_paly = setInterval(() => { //再开户定时器
					this.vue_deg_num += 6;
					this.$refs['loadingIcon']['style']['transform'] = "rotate(" + this.vue_deg_num + "deg)";
					this.$refs['loadingIcon']['style']['-webkit-transform'] = "rotate(" + this.vue_deg_num + "deg)";
				}, 13)
			},
			vFun_messageHistory() {
				console.log("进入获取历史记录。。。。1111");
				let __this = this;
				var $scope = new Object();
				$scope.targetType = 1; //1：私聊
				var config = {
					appkey: this.rong_key,
					token: this.rong_token
				};
				var msgObj = {
					type: 　$scope.targetType,
					targetId: this.rong_targetId,
				};

				this.RongcloudCommon.login(config, {
					// 接收到的消息
					onReceived: function(message) {
						var msg = __this.RongcloudMessage.convertMsg(message);

						// 判断消息类型
						switch(message.messageType) {
							case RongIMClient.MessageType.TextMessage:
								// message.content.content => 消息内容
								console.log("接收到的消息" + message.content.content + "********");
								var senderUserId = msg.senderUserId;
								__this.$set(__this.vue_listData,__this.vue_listData.length,{
									userHead: (senderUserId != null && senderUserId == msg.targetId) ? require('../../assets/images/logo1.jpg') : require('../../assets/images/logo10.jpg'),
									userName: (senderUserId != null && senderUserId == msg.targetId) ? "" : "my",
									userSay: msg.content.content,
									start: '',
									num: '0'
								});
								setTimeout(() => {
									window.scrollTo(0, __this.$refs['chatPage'].clientHeight) //页面滚动到底部
								}, 10);

								break;
							case RongIMClient.MessageType.VoiceMessage:
								// 对声音进行预加载
								// message.content.content 格式为 AMR 格式的 base64 码
								break;
							case RongIMClient.MessageType.ImageMessage:
								// message.content.content => 图片缩略图 base64。
								// message.content.imageUri => 原图 URL。
								break;
							case RongIMClient.MessageType.DiscussionNotificationMessage:
								// message.content.extension => 讨论组中的人员。
								break;
							case RongIMClient.MessageType.LocationMessage:
								// message.content.latiude => 纬度。
								// message.content.longitude => 经度。
								// message.content.content => 位置图片 base64。
								break;
							case RongIMClient.MessageType.RichContentMessage:
								// message.content.content => 文本消息内容。
								// message.content.imageUri => 图片 base64。
								// message.content.url => 原图 URL。
								break;
							case RongIMClient.MessageType.InformationNotificationMessage:
								// do something...
								break;
							case RongIMClient.MessageType.ContactNotificationMessage:
								// do something...
								break;
							case RongIMClient.MessageType.ProfileNotificationMessage:
								// do something...
								break;
							case RongIMClient.MessageType.CommandNotificationMessage:
								// do something...
								break;
							case RongIMClient.MessageType.CommandMessage:
								// do something...
								break;
							case RongIMClient.MessageType.UnknownMessage:
								// do something...
								break;
							default:
								// do something...
						}
					}
				});
				//debugger;

				this.RongcloudMessage.queryByPage(config, msgObj, {
					onSuccess: function(list, hasMsg) {
						var msglen = list.length;
						var msgList = [];
						var len = __this.vue_listData.length ;
						while(msglen--) {
							var msg = __this.RongcloudMessage.convertMsg(list[msglen]);
							var senderUserId = msg.senderUserId;
							var index = (len > 0) ? len : msglen;
							msgList[index] = {
								userHead: (senderUserId != null && senderUserId == msgObj.targetId) ?  require('../../assets/images/logo1.jpg') : require('../../assets/images/logo10.jpg'),
								userName: (senderUserId != null && senderUserId == msgObj.targetId) ? "" : "my",
								userSay: msg.content.content,
								start: '',
								num: '0'
							};
						}
						__this.vue_listData = msgList;
						console.log(__this.vue_listData);
					},
					onError: function(error) {
						console.log('获取历史记录失败：' + error);
					}
				});
				let arr = __this.vue_listData;
				return arr;
			},
			vFun_loading_btn() {
				clearInterval(this.vue_deg_paly);  //先清除之前的定时器
				this.vue_loading_btnShow=false;  //隐藏点击按钮，显示加载中
				this.vFun_loading_play();
				setTimeout(()=>{
					this.vue_listData.unshift({  //更新数据
						userHead:require('../../assets/images/logo1.jpg'),
						userName:'张三',
						userSay:'在吗11？',
						start:'left',
						num:'100',
					},);
					this.vue_loading_btnShow=true;
					clearInterval(this.vue_deg_paly);  //清除定时器
				}, 1000)
			},
			vFun_emojis_select(e) { //选择单个表情
				let emojisSpan = e.getElementsByTagName('span')[0];
				var dd = emojisSpan.getAttribute('name');
				var str = RongIMLib.RongIMEmoji.symbolToEmoji(dd);
				this.vue_chat_mySay += str;
			},

		},
		created() {
		},
		updated() {
			this.vue_chatDetailList_oldHeight = this.$refs['listWrap'].clientHeight;
		},
		mounted() {
			RongIMLib.RongIMEmoji.init(); //初始化表情库
			this.vue_emojis = RongIMLib.RongIMEmoji.emojis; //获取所有表情

			const _this = this;
			window.onresize = () => { //挂载window的resize事件
				return(() => {
					this.vue_keyboard_show = !(document.documentElement.clientHeight > _this.vue_screenHeight); //判断键盘有没有弹出
					_this.vue_screenHeight = document.documentElement.clientHeight; //用于监听window.resize
					window.scrollTo(0, this.$refs['chatPage'].clientHeight) //页面滚动到底部
				})()
			};
			this.$refs['listWrap'].style.marginBottom = this.$refs['footer'].clientHeight + 'px'; //动态给list加底部margin,让聊天记录显示在输入框上面。
			window.scrollTo(0, this.$refs['chatPage'].clientHeight) //页面滚动到底部
			this.vue_chatDetailList_oldHeight = this.$refs['listWrap'].clientHeight;
			this.$refs['emojis'].ontouchmove = function(event) { //touchmove时禁掉touchend事件，避免滑动表情时选择了表情
				var flag = false;
				window.addEventListener('touchmove', function(ev) {
					flag || (flag = true, window.addEventListener('touchend', stopTouchendPropagation, true));
				}, false);

				function stopTouchendPropagation(ev) {
					ev.stopPropagation();
					setTimeout(function() {
						window.removeEventListener('toucvFun_userInfohend', stopTouchendPropagation, true);
						flag = false;
					}, 50);
				}
			}

			this.vFun_userInfo(); //获取当前用户融云信息，获取完成后读取会话历史消息
		},
	}

</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
	.header {
		height: 56px;
	}

	.list {
		background: #fbf9f9;
		overflow-y: auto;
	}

	.demo-icon-badge {
		position: absolute;
		left: 40px;
		top: 0;
	}

	.contentDiv {
		display: inline-block;
		position: relative;
		max-width: 80%;
		width: auto;
		background: #fff;
		border-radius: 3px;
		border: 1px solid #c0c0c0;
	}

	.otherSay .contentDiv:after {
		content: '';
		position: absolute;
		width: 8px;
		height: 8px;
		background: #fff;
		transform: rotate(-45deg);
		border-top: 1px solid #c0c0c0;
		border-left: 1px solid #c0c0c0;
		top: 5px;
		left: -5px;
	}

	.mySay .contentDiv {
		float: right;
		margin-right: 15px;
	}

	.mySay .contentDiv:after {
		content: '';
		position: absolute;
		width: 8px;
		height: 8px;
		background: #fff;
		transform: rotate(135deg);
		border-top: 1px solid #c0c0c0;
		border-left: 1px solid #c0c0c0;
		top: 5px;
		right: -5px;
	}

	.footer {
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		background: #fff;
		padding: 5px;
	}

	.inputBtn {
		display: flex;
		padding-left: 8px;
		line-height: 1;
	}

	.input {
		flex: auto;
	}

	.button {
		flex-basis: 100px;
		align-self: center;
		vertical-align: middle;
	}

	.em.iconfont {
		font-size: 28px;
		vertical-align: middle;
	}

	.demo-raised-button {
		height: auto;
		line-height: auto;
		min-width: 0;
		padding: 7px 10px;
	}

	.emojis {
		width: 100%;
		height: auto;
		padding: 5px;
	}

	.emojis>ul {
		width: 100%;
		height: 100px;
		overflow-y: auto;
		background: #fff;
		padding: 0 10px 0 15px;
	}

	.emojis>ul>li {
		padding: 5px;
		margin-right: 3px;
	}

	.loadingText {
		height: 18px;
		line-height: 18px;
		text-align: center;
	}

	.loading {
		display: inline-block;
		height: 18px;
		line-height: 18px;
		vertical-align: middle;
	}

	.loading i.iconfont {
		display: inline-block;
		position: relative;
		top: -1px;
		width: 18px;
		height: 18px;
		line-height: 18px;
		text-align: center;
		vertical-align: middle;
		border: 2px solid #c0c0c0;
		border-radius: 50%;
		border-left-color: #fbf9f9;
	}

	.loadBtn {
		text-decoration: underline;
		color: #2196F3;
	}
</style>
